<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>产品详情</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- 引入jQuery -->
    <link rel="stylesheet" href="css/product-detail.css">
    <!-- 引入CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <!-- 新增图标库 -->
    <link href="https://fonts.googleapis.com/css2?family=ZCOOL+XiaoWei&display=swap" rel="stylesheet">
    <style>
        /* 整体背景色 */
        body {
            background-color: #fff9e6;
            margin: 0;
            padding: 0;
        }

        /* 美化搜索框 */
        .search-bar {
            background: white;
            border-radius: 20px;
            padding: 8px 15px;
            display: flex;
            align-items: center;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            width: 300px;
            margin: 0 auto;
        }

        .search-bar input {
            border: none;
            outline: none;
            width: 100%;
            padding: 5px;
            font-size: 14px;
        }

        .search-bar i {
            color: #666;
            cursor: pointer;
        }

        /* 卖家信息头部 */
        .seller-header {
            background: white;
            padding: 15px 20px;
            border-radius: 12px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            margin-bottom: 20px;
            max-width: 1200px;
            margin: 20px auto;
        }

        .seller-info {
            display: flex;
            align-items: center;
        }

        .seller-avatar img {
            width: 48px;
            height: 48px;
            border-radius: 50%;
            margin-right: 12px;
        }

        .seller-details {
            flex: 1;
        }

        .seller-name {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 4px;
        }

        .seller-rating {
            color: #ff4400;
            font-size: 14px;
            margin-top: 5px;
        }

        .seller-rating i {
            margin-right: 2px;
        }

        .follow-btn {
            padding: 6px 15px;
            border: 1px solid #ff4400;
            color: #ff4400;
            background: white;
            border-radius: 4px;
            cursor: pointer;
        }

        /* 主容器样式 */
        .product-container {
            display: flex;
            max-width: 1200px;
            margin: 0 auto;
            gap: 40px;
            padding: 0 20px;
        }

        /* 左侧图片区域 */
        .product-left {
            flex: 0 0 600px;
            background: white;
            padding: 20px;
            border-radius: 20px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }

        .main-image {
            width: 600px;
            height: 600px;
            position: relative;
            margin-bottom: 20px;
            border-radius: 15px;
            overflow: hidden;
        }

        .main-image img {
            width: 100%;
            height: 100%;
            object-fit: contain;
        }

        .prev-btn, .next-btn {
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
            background: rgba(0, 0, 0, 0.3);
            color: white;
            border: none;
            padding: 15px 20px;
            cursor: pointer;
            font-size: 20px;
            opacity: 0;
            transition: opacity 0.3s;
        }

        .main-image:hover .prev-btn,
        .main-image:hover .next-btn {
            opacity: 1;
        }

        .prev-btn { left: 10px; }
        .next-btn { right: 10px; }

        .thumbnail-list {
            display: flex;
            gap: 10px;
            overflow-x: auto;
            padding: 10px 0;
        }

        .thumbnail {
            width: 70px;
            height: 70px;
            border: 2px solid transparent;
            cursor: pointer;
            flex-shrink: 0;
            transition: border-color 0.3s;
        }

        .thumbnail.active {
            border-color: #ff4400;
        }

        .thumbnail img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        /* 右侧信息区域 */
        .product-right {
            flex: 1;
            background: white;
            padding: 20px;
            border-radius: 12px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }

        .product-name {
            font-size: 24px;
            line-height: 1.4;
            margin-bottom: 20px;
            font-family: 'ZCOOL XiaoWei', serif;
            color: #333;
            padding: 10px 0;
            position: relative;
        }

        .price-section {
            margin-bottom: 20px;
            padding: 15px 0;
            border-bottom: 1px solid rgba(0, 0, 0, 0.05);
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
        }

        .price-row {
            display: flex;
            align-items: baseline;
            margin-bottom: 10px;
        }

        .current-price {
            color: #ff4400;
            font-size: 30px;
            font-weight: bold;
            margin-right: 15px;
        }

        .original-price {
            color: #999;
            text-decoration: line-through;
            font-size: 16px;
        }

        .product-stats {
            color: #999;
            font-size: 14px;
            margin-bottom: 30px;
        }

        .product-stats span {
            margin-right: 20px;
        }

        .action-buttons {
            display: flex;
            gap: 15px;
            margin-top: 30px;
            padding: 15px;
            background: linear-gradient(to right, #fff9e6, #fff);
            border-radius: 8px;
        }

        .action-btn {
            flex: 1;
            height: 44px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            transition: transform 0.2s;
        }

        .action-btn:hover {
            transform: translateY(-2px);
        }

        .buy-now {
            background: #ff4400;
            color: white;
            font-family: 'ZCOOL XiaoWei', serif;
            font-size: 18px;
            letter-spacing: 2px;
            text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
        }

        /* 商品新旧程度标签 */
        .condition-tag {
            display: inline-block;
            padding: 4px 10px;
            font-size: 14px;
            text-align: center;
            position: relative;
            margin-left: 15px;
        }

        .condition-5 {
            background: linear-gradient(45deg, #e8f7f2, #f2f9f6);
            color: #00a06d;
            box-shadow: 0 2px 6px rgba(0, 160, 109, 0.1);
        }

        .condition-4 {
            background: linear-gradient(45deg, #fff3e0, #fff7eb);
            color: #ff8c00;
            box-shadow: 0 2px 6px rgba(255, 140, 0, 0.1);
        }

        .condition-3 {
            background: linear-gradient(45deg, #f5f5f5, #fafafa);
            color: #666;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
        }

        .condition-2 {
            background: linear-gradient(45deg, #fff0f0, #fff5f5);
            color: #ff4444;
            box-shadow: 0 2px 6px rgba(255, 68, 68, 0.1);
        }

        .condition-1 {
            background: linear-gradient(45deg, #ffe0e0, #fff0f0);
            color: #cc0000;
            box-shadow: 0 2px 6px rgba(204, 0, 0, 0.1);
        }

        .action-btn span {
            font-family: 'ZCOOL XiaoWei', serif;
            font-size: 16px;
        }

        .product-description {
            background: linear-gradient(135deg, #fff9e6, #fff);
            padding: 15px;
            border-radius: 8px;
            margin-top: 20px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.02);
        }

        .product-description h3 {
            color: #666;
            position: relative;
            padding-bottom: 10px;
            margin-bottom: 15px;
            font-family: 'ZCOOL XiaoWei', serif;
            font-size: 20px;
            display: inline-block;
        }

        .product-description h3::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 2px;
            background: linear-gradient(to right, #ffe100, transparent);
        }

        /* 添加留言区域样式 */
        .message-section {
            max-width: 1200px;
            margin: 40px auto;
            padding: 0 20px;
        }

        .message-container {
            background: white;
            border-radius: 20px;
            padding: 30px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }

        .message-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .message-header h3 {
            font-family: 'ZCOOL XiaoWei', serif;
            font-size: 20px;
            color: #333;
            margin: 0;
        }

        .message-input {
            margin-bottom: 30px;
        }

        .message-input textarea {
            width: 100%;
            height: 100px;
            padding: 15px;
            border: 1px solid #eee;
            border-radius: 10px;
            resize: none;
            margin-bottom: 15px;
            font-size: 14px;
        }

        .message-input button {
            background: #ff4400;
            color: white;
            border: none;
            padding: 10px 25px;
            border-radius: 20px;
            cursor: pointer;
            font-family: 'ZCOOL XiaoWei', serif;
            font-size: 16px;
        }

        .message-list {
            border-top: 1px solid #eee;
            padding-top: 20px;
        }

        .message-item {
            padding: 20px 0;
            border-bottom: 1px solid #f5f5f5;
        }

        .message-item:last-child {
            border-bottom: none;
        }

        .message-user-info {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
        }

        .message-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            margin-right: 10px;
            object-fit: cover;
            border: 1px solid #eee;
        }

        .message-user-meta {
            flex: 1;
        }

        .message-username {
            font-weight: bold;
            color: #333;
            margin-bottom: 3px;
        }

        .message-time {
            font-size: 12px;
            color: #999;
        }

        .message-content {
            margin: 10px 0;
            color: #333;
            line-height: 1.5;
            padding-left: 50px;
        }

        .message-actions {
            text-align: right;
            padding-left: 50px;
        }

        .reply-btn {
            color: #666;
            background: none;
            border: none;
            cursor: pointer;
            font-size: 14px;
            padding: 5px 10px;
            opacity: 0.7;
            transition: all 0.3s;
        }

        .reply-btn:hover {
            color: #ff4400;
            opacity: 1;
        }

        /* 修改回复框 */
        .reply-form {
            margin: 10px 0;
            padding: 10px;
            background: #f9f9f9;
            border-radius: 8px;
            display: none;
            position: relative;
        }

        .reply-form.active {
            display: block;
        }

        /* 回复框的位置根据是否是回复来调整 */
        .message-item > .reply-form {
            margin-left: 50px;
        }

        .reply-messages .reply-form {
            margin: 10px 15px;
        }

        .reply-form textarea {
            width: 100%;
            height: 60px;
            padding: 10px;
            border: 1px solid #eee;
            border-radius: 8px;
            resize: none;
            margin-bottom: 10px;
            transition: border-color 0.3s;
        }

        .reply-form textarea:focus {
            border-color: #ff4400;
            outline: none;
        }

        .reply-form button {
            background: #ff4400;
            color: white;
            border: none;
            padding: 5px 15px;
            border-radius: 15px;
            cursor: pointer;
            font-size: 14px;
        }

        /* 回复消息样式 */
        .reply-messages {
            margin-left: 50px;
            padding: 10px 0;
            border-left: 2px solid #f0f0f0;
            background: #fafafa;
            border-radius: 0 8px 8px 0;
        }

        .reply-messages .message-item {
            padding: 15px 20px;
            border-bottom: 1px solid #eee;
            position: relative;
        }

        .reply-messages .message-item:hover {
            background: #fff;
        }

        .reply-messages .message-actions {
            opacity: 0;
            transition: opacity 0.3s;
        }

        .reply-messages .message-item:hover .message-actions {
            opacity: 1;
        }

        /* 标样式 */
        .seller-tag {
            display: inline-block;
            background: #ffe100;
            color: white;
            font-size: 12px;
            padding: 2px 6px;
            border-radius: 4px;
            margin-left: 6px;
            font-weight: normal;
            color: #333;
            box-shadow: 0 2px 4px rgba(255, 225, 0, 0.2);
        }

        /* 回复对象样式 */
        .reply-to {
            color: #666;
            font-size: 14px;
            margin-right: 5px;
        }

        /* 添加提示框样式 */
        .message-alert {
            position: fixed;
            bottom: 20px;
            left: 50%;
            transform: translateX(-50%);
            background: rgba(0, 0, 0, 0.7);
            color: white;
            padding: 10px 20px;
            border-radius: 20px;
            font-size: 14px;
            z-index: 1000;
            animation: fadeInOut 2s ease-in-out;
        }

        @keyframes fadeInOut {
            0% { opacity: 0; transform: translate(-50%, 20px); }
            20% { opacity: 1; transform: translate(-50%, 0); }
            80% { opacity: 1; transform: translate(-50%, 0); }
            100% { opacity: 0; transform: translate(-50%, -20px); }
        }

        .favorite-btn {
            padding: 8px 20px;
            border: 1px solid #ffd700;
            background: white;
            color: #ffd700;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .favorite-btn.favorited {
            background: #ffd700;
            color: white;
        }

        .alert-box {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: rgba(0, 0, 0, 0.7);
            color: white;
            padding: 15px 30px;
            border-radius: 25px;
            z-index: 1000;
            animation: fadeIn 0.3s ease-in;
        }

        .alert-box.fade-out {
            animation: fadeOut 0.5s ease-out;
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        @keyframes fadeOut {
            from { opacity: 1; }
            to { opacity: 0; }
        }

        .product-container {
            max-width: 1200px;
            margin: 20px auto;
            padding: 20px;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }

        .product-header {
            display: flex;
            gap: 40px;
            margin-bottom: 30px;
        }

        .product-images {
            width: 400px;
            border-radius: 8px;
            overflow: hidden;
        }

        .main-image {
            width: 100%;
            height: 400px;
            object-fit: cover;
        }

        .thumbnail-list {
            display: flex;
            gap: 10px;
            margin-top: 10px;
        }

        .thumbnail {
            width: 60px;
            height: 60px;
            object-fit: cover;
            border-radius: 4px;
            cursor: pointer;
            border: 2px solid transparent;
            transition: all 0.3s;
        }

        .thumbnail:hover, .thumbnail.active {
            border-color: #ff4400;
        }

        .product-info {
            flex: 1;
        }

        .product-title {
            font-size: 24px;
            font-weight: bold;
            margin-bottom: 15px;
            color: #333;
        }

        .price-section {
            background: #fff9f9;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
        }

        .price {
            font-size: 28px;
            color: #ff4400;
            font-weight: bold;
        }

        .original-price {
            font-size: 16px;
            color: #999;
            text-decoration: line-through;
            margin-left: 10px;
        }

        .seller-info {
            display: flex;
            align-items: center;
            padding: 15px;
            background: #f8f8f8;
            border-radius: 8px;
            margin-bottom: 20px;
        }

        .seller-avatar {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            margin-right: 15px;
        }

        .seller-name {
            font-weight: bold;
            color: #333;
        }

        .seller-rating {
            color: #ff4400;
            margin-top: 5px;
        }

        .action-buttons {
            display: flex;
            gap: 15px;
            margin-top: 30px;
        }

        .action-btn {
            padding: 12px 30px;
            border-radius: 4px;
            font-size: 16px;
            cursor: pointer;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .buy-now {
            background: #ff4400;
            color: white;
            border: none;
        }

        .buy-now:hover {
            background: #ff2200;
        }

        .chat-btn {
            background: #fff5f0;
            color: #ff4400;
            border: 1px solid #ff4400;
        }

        .chat-btn:hover {
            background: #fff0e6;
        }

        .favorite-btn {
            background: white;
            color: #666;
            border: 1px solid #ddd;
        }

        .favorite-btn:hover {
            border-color: #ff4400;
            color: #ff4400;
        }

        .favorite-btn.favorited {
            background: #fff5f0;
            color: #ff4400;
            border-color: #ff4400;
        }

        .manage-btn {
            background: #4a90e2;
            color: white;
            border: none;
            width: 100%;
        }

        .manage-btn:hover {
            background: #357abd;
        }

        .product-description {
            margin-top: 40px;
            padding-top: 30px;
            border-top: 1px solid #eee;
        }

        .description-title {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 20px;
            color: #333;
        }

        .description-content {
            color: #666;
            line-height: 1.6;
        }

        /* 移除旧的信用等级样式 */
        .credit-score {
            display: none;
        }

        /* 星级评分样式 */
        .seller-rating {
            color: #ff4400;
            font-size: 14px;
            margin-top: 5px;
            display: flex;
            align-items: center;
            gap: 2px;
        }

        .seller-rating i {
            color: #ffd700;
        }

        .seller-rating .far.fa-star {
            color: #ddd;
        }

        .rating-score {
            margin-left: 5px;
            color: #666;
            font-size: 12px;
        }
    </style>

</head>

<body>
    <header class="top-bar">
        <div class="back-button">
            <a href="home.html"><i class="fas fa-arrow-left"></i></a>
        </div>
        <div class="search-bar">
            <input type="text" placeholder="搜索">
            <i class="fas fa-search"></i>
        </div>
        <div class="header-icons">
            <a href="#" onclick="checkLogin()"><i class="fas fa-shopping-cart"></i></a>
            <i class="fas fa-ellipsis-v"></i>
        </div>
    </header>

    <main>
        <!-- 卖家信息区域 -->
        <div class="seller-header">
            <div class="seller-info">
                <div class="seller-avatar" onclick="location.href='user-profile.html?id=' + window.productData.data[0].sellerId" style="cursor: pointer;">
                    <img src="" alt="卖家头像">
                </div>
                <div class="seller-details">
                    <div class="seller-name" onclick="location.href='user-profile.html?id=' + window.productData.data[0].sellerId" style="cursor: pointer;"></div>
                    <div class="seller-rating">
                        <i class="fas fa-star"></i>
                        <i class="fas fa-star"></i>
                        <i class="fas fa-star"></i>
                        <i class="fas fa-star"></i>
                        <i class="fas fa-star-half-alt"></i>
                    </div>
                </div>
            </div>
        </div>

        <div class="product-container">
            <!-- 左侧图片展示区 -->
            <div class="product-left">
                <!-- 大图展示 -->
                <div class="main-image">
                    <img src="" alt="产品大图" id="mainImage">
                    <button class="prev-btn">❮</button>
                    <button class="next-btn">❯</button>
                </div>
                <!-- 缩略图列表 -->
                <div class="thumbnail-list">
                    <!-- 缩略图将通过JavaScript动态填充 -->
                </div>
            </div>

            <!-- 右侧商品信息区 -->
            <div class="product-right">
                <div class="price-section">
                    <div class="price-info">
                        <div class="price-row">
                            <div class="current-price">
                                <span class="price-symbol">¥</span>
                                <span class="product-price">0.00</span>
                            </div>
                            <div class="original-price">原价 ¥<span id="originalPrice">0.00</span></div>
                        </div>
                        <div class="product-stats">
                            <span class="views">浏览 <span id="viewCount">0</span></span>
                            <span class="likes">获赞 <span id="likeCount">0</span></span>
                        </div>
                    </div>
                    <div class="condition-wrapper">
                        <span class="condition-tag" id="conditionTag">全新</span>
                    </div>
                </div>

                <div class="product-info">
                    <h1 class="product-name">加载中...</h1>
                </div>

                <!-- 商品描述 -->
                <div class="product-description">
                    <h3>商品描述</h3>
                    <div class="product-details">加载中...</div>
                </div>

                <!-- 操作按钮 -->
                <div class="action-buttons">
                    <button class="action-btn buy-now">立即购买</button>
                    <button class="action-btn chat">
                        <i class="fas fa-comment"></i>
                        <span>我想要</span>
                    </button>
                    <button class="action-btn favorite">
                        <i class="fas fa-heart"></i>
                        <span>收藏</span>
                    </button>
                </div>
            </div>
        </div>

        <!-- 留言区域 -->
        <div class="message-section">
            <div class="message-container">
                <div class="message-header">
                    <h3>商品留言</h3>
                </div>
                <div class="message-input">
                    <textarea id="messageContent" placeholder="请输入留言内容..."></textarea>
                    <button onclick="submitMessage()">发送留言</button>
                </div>
                <div class="message-list" id="messageList">
                    <!-- 留言内容将通过JavaScript动态填充 -->
                </div>
            </div>
        </div>
    </main>

    <script>
        // 添加全局变量存储当前用户ID
        let currentUserId = null;

        // 修改页面加载函数
        $(document).ready(function() {
            // 先获取当前登录用户信息
            $.ajax({
                url: '/user/get-user',
                type: 'GET',
                success: function(userResponse) {
                    if (userResponse.state === 1) {
                        currentUserId = userResponse.data.id;
                    }
                    // 无论是否登录都加载商品信息
                    loadProductDetail();
                },
                error: function() {
                    // 未登录也允许查看商品详情
                    loadProductDetail();
                }
            });
        });

        // 修改商品详情加载函数
        function loadProductDetail() {
            const productId = new URLSearchParams(window.location.search).get('id');
            if (!productId) {
                alert('商品ID不能为空');
                return;
            }

            $.ajax({
                url: `/product/detail?id=${productId}`,
                type: 'GET',
                success: function(response) {
                    if (response.state === 1) {
                        console.log(response);
                        window.productData = response;
                        const product = response.data[0];
                        
                        // 添加浏览历史记录
                        if (currentUserId) {
                            $.ajax({
                                url: '/history/add',
                                type: 'POST',
                                contentType: 'application/json',
                                data: JSON.stringify({
                                    productId: product.id,
                                    productName: product.name,
                                    productPrice: product.price,
                                    productImage: product.images ? (typeof product.images === 'string' ? JSON.parse(product.images)[0] : product.images[0]) : null,
                                    isAuction: false
                                }),
                                success: function(historyResponse) {
                                    console.log('浏览历史添加成功:', historyResponse);
                                },
                                error: function(err) {
                                    console.error('添加浏览历史失败:', err);
                                }
                            });
                        }
                        
                        // 判断是否是商品拥有者
                        const isOwner = currentUserId && currentUserId === product.sellerId;
                        
                        // 更新商品信息
                        $('.product-title').text(product.name);
                        $('.price').text(`¥${product.price}`);
                        if (product.originalPrice) {
                            $('.original-price').text(`¥${product.originalPrice}`);
                        }
                        
                        // 更新卖家信息
                        $('.seller-avatar img').attr('src', product.sellerAvatar || 'default-avatar.png');
                        $('.seller-name').text(product.sellerNickname || product.sellerUsername); // 优使用昵称
                        
                        // 更新操作按钮
                        const actionButtons = $('.action-buttons');
                        if (isOwner) {
                            actionButtons.html(`
                                <button class="action-btn manage-btn" onclick="manageProduct(${product.id})">
                                    <i class="fas fa-edit"></i>管理商品
                                </button>
                            `);
                        } else {
                            actionButtons.html(`
                                <button class="action-btn buy-now" onclick="location.href='order-confirm.html?pid=${product.id}'">
                                    <i class="fas fa-shopping-cart"></i>立即购买
                                </button>
                                <button class="action-btn chat-btn" onclick="window.open('chat.html?sellerId=${product.sellerId}&productId=${product.id}', '_blank')">
                                    <i class="fas fa-comments"></i>我想要
                                </button>
                                <button id="favoriteBtn" class="action-btn favorite-btn" onclick="toggleFavorite()">
                                    <i class="far fa-heart"></i>收藏
                                </button>
                            `);
                            
                            // 如果已登录，检查收藏状态
                            if (currentUserId) {
                                checkFavorite();
                            }
                        }
                    }
                }
            });
        }

        // 修改生成星级评分的函数
        function generateStarRating(score) {
            let ratingHtml = '';
            const roundedScore = Math.round(score * 2) / 2; // 将���数四舍五入到最近的0.5
            
            // 生成实心星星
            for (let i = 1; i <= Math.floor(roundedScore); i++) {
                ratingHtml += '<i class="fas fa-star"></i>';
            }
            
            // 处理半星
            if (roundedScore % 1 !== 0) {
                ratingHtml += '<i class="fas fa-star-half-alt"></i>';
            }
            
            // 生成空心星星
            const emptyStars = 5 - Math.ceil(roundedScore);
            for (let i = 0; i < emptyStars; i++) {
                ratingHtml += '<i class="far fa-star"></i>';
            }
            
            // 添加数字评分
            ratingHtml += `<span class="rating-score">(${score.toFixed(1)})</span>`;
            
            return ratingHtml;
        }

        // 添加商品管理功能
        function manageProduct(productId) {
            location.href = `product-edit.html?id=${productId}`;
        }

        // 检查用户是否登录
        function checkLogin() {
            $.ajax({
                url: "/user/get-user",
                type: "get",
                success: function (result) {
                    console.log(result);
                    if (result.state == 401) {
                        if (confirm("你尚未登录，是否前往登录���")) {
                            location.href = "login.html";
                        }
                    }
                    if (result.state == 200) {
                        location.href = "shoppingcart.html";
                    }
                },
                error: function (err) {
                    if (err.status == 401) {
                        alert("当前用户未登录，你将回到首页");
                        location.href = "home.html";
                    }
                }
            });
        }

        const urlParams = new URLSearchParams(window.location.search);
        const productId = urlParams.get('id'); // 获取 productId
        $.ajax({
            url: "/product/detail",
            type: "GET",
            dataType: "json",
            data: {
                id: productId
            },
            success: function (product) {
                updateProductDetails(product);
                getMessages(); // 获取产品评论
            },
            error: function () {
                alert("获取产品详情失败");
            }
        });

        // 获取地址信息
        getAddress();
        const addressSelectElement = document.getElementById('address');
        function getAddress() {
            $.ajax({
                url: "/user/get-address",
                type: "GET",
                dataType: "json",
                success: function (address) {
                    addressSelectElement.innerHTML = `<option value="${address.data.address}">${address.data.address}</option>`;
                },
                error: function () { }
            });
        }

        function updateProductDetails(product) {
            // 保存商品数据到全局变量供其他函数使用
            window.productData = product;
            
            // 更新卖家信息
            const sellerAvatar = document.querySelector('.seller-avatar img');
            const sellerName = document.querySelector('.seller-name');
            const sellerRating = document.querySelector('.seller-rating');
            
            sellerAvatar.src = product.data[0].sellerAvatar || 'default-avatar.png';
            sellerName.textContent = product.data[0].sellerNickname || product.data[0].sellerUsername;
            
            // 使用星级评分替代数字显示
            const creditScore = product.data[0].sellerCreditScore || 4;
            sellerRating.innerHTML = generateStarRating(creditScore);

            // 更新商品基本信息
            document.querySelector('.product-name').textContent = product.data[0].name;
            document.querySelector('.product-price').textContent = product.data[0].price;
            document.getElementById('originalPrice').textContent = product.data[0].originalPrice;
            document.querySelector('.product-details').textContent = product.data[0].description;
            document.getElementById('viewCount').textContent = product.data[0].viewCount || 0;
            document.getElementById('likeCount').textContent = product.data[0].favoriteCount || 0;

            // 处理图片显示
            try {
                let imageUrls = product.data[0].images;
                if (typeof imageUrls === 'string') {
                    imageUrls = JSON.parse(imageUrls);
                }
                
                // 设置主图
                document.getElementById('mainImage').src = imageUrls[0];
                
                // 生成缩略图
                const thumbnailList = document.querySelector('.thumbnail-list');
                thumbnailList.innerHTML = imageUrls.map((url, index) => `
                    <div class="thumbnail ${index === 0 ? 'active' : ''}" onclick="showImage(${index})">
                        <img src="${url}" alt="缩略图 ${index + 1}">
                    </div>
                `).join('');
                
                // 存储图片数组
                window.productImages = imageUrls;
                window.currentImageIndex = 0;

                // 添加前后按钮点击事件
                document.querySelector('.prev-btn').onclick = prevImage;
                document.querySelector('.next-btn').onclick = nextImage;
            } catch (e) {
                console.error('图片处理失败:', e);
                document.getElementById('mainImage').src = 'default-product-image.jpg';
            }

            // 判断是否是商品所有者并更新按钮
            const isOwner = currentUserId && currentUserId === product.data[0].sellerId;
            const actionButtons = $('.action-buttons');
            if (isOwner) {
                actionButtons.html(`
                    <button class="action-btn manage-btn" onclick="manageProduct(${product.data[0].id})">
                        <i class="fas fa-edit"></i>管理商品
                    </button>
                `);
            } else {
                actionButtons.html(`
                    <button class="action-btn buy-now" onclick="location.href='order-confirm.html?pid=${product.data[0].id}'">
                        <i class="fas fa-shopping-cart"></i>立即购买
                    </button>
                    <button class="action-btn chat-btn" onclick="window.open('chat.html?sellerId=${product.data[0].sellerId}&productId=${product.data[0].id}', '_blank')">
                        <i class="fas fa-comments"></i>我想要
                    </button>
                    <button id="favoriteBtn" class="action-btn favorite-btn" onclick="toggleFavorite()">
                        <i class="far fa-heart"></i>收藏
                    </button>
                `);
                
                // 如果已登录，检查收藏状态
                if (currentUserId) {
                    checkFavorite();
                }
            }
        }

        // 添加图片轮播相关函数
        function showImage(index) {
            const mainImage = document.querySelector('#mainImage');
            const thumbnails = document.querySelectorAll('.thumbnail');
            
            mainImage.src = window.productImages[index];
            window.currentImageIndex = index;
            
            // 更新略图激活状态
            thumbnails.forEach((thumb, i) => {
                thumb.classList.toggle('active', i === index);
            });
        }

        function prevImage() {
            let newIndex = window.currentImageIndex - 1;
            if (newIndex < 0) {
                newIndex = window.productImages.length - 1;
            }
            showImage(newIndex);
        }

        function nextImage() {
            let newIndex = window.currentImageIndex + 1;
            if (newIndex >= window.productImages.length) {
                newIndex = 0;
            }
            showImage(newIndex);
        }

        // 获取产品评论
        function getMessages() {
            $.ajax({
                url: `/message/get-all`,
                type: "GET",
                dataType: "json",
                data: {
                    pid: productId
                },
                success: function(response) {
                    if (response.state === 1 && response.data) {
                        displayMessages(response.data);
                    } else {
                        console.log(response);
                        console.error('Failed to get messages:', response.msg);
                    }
                },
                error: function(err) {
                    console.error('Error fetching messages:', err);
                    alert("获取留言失败");
                }
            });
        }

        function displayMessages(messages) {
            if (!messages || !Array.isArray(messages)) {
                console.error('No messages or invalid message format');
                return;
            }

            console.log('Messages to display:', messages);

            const messageList = document.querySelector('.message-list');
            messageList.innerHTML = '';

            messages.forEach(message => {
                console.log('Processing message:', message);
                const isSellerMessage = message.senderId === window.productData.data[0].sellerId;
                const messageDiv = document.createElement('div');
                messageDiv.className = 'message-item';
                messageDiv.innerHTML = `
                    <div class="message-user-info">
                        <img class="message-avatar" src="${message.senderAvatar || 'default-avatar.png'}" 
                             onerror="this.src='default-avatar.png'" alt="用户头像">
                        <div class="message-user-meta">
                            <div class="message-username">
                                ${message.senderNickname}
                                ${isSellerMessage ? '<span class="seller-tag">商家</span>' : ''}
                            </div>
                            <div class="message-time">${new Date(message.createTime).toLocaleString()}</div>
                        </div>
                    </div>
                    <div class="message-content">${message.content}</div>
                    <div class="message-actions">
                        <button class="reply-btn" onclick="showReplyForm(${message.id}, '${message.senderNickname}')">
                            <i class="fas fa-reply"></i> 回复
                        </button>
                    </div>
                    <div class="reply-form" id="replyForm-${message.id}">
                        <textarea placeholder="回复 ${message.senderNickname}..."></textarea>
                        <button onclick="submitReply(${message.id}, '${message.senderNickname}')">发送回复</button>
                    </div>
                    ${message.replies && message.replies.length > 0 ? `
                        <div class="reply-messages">
                            ${message.replies.map(reply => {
                                const isSellerReply = reply.senderId === window.productData.data[0].sellerId;
                                return `
                                    <div class="message-item">
                                        <div class="message-user-info">
                                            <img class="message-avatar" src="${reply.senderAvatar || 'default-avatar.png'}"
                                                 onerror="this.src='default-avatar.png'" alt="用户头像">
                                            <div class="message-user-meta">
                                                <div class="message-username">
                                                    ${reply.senderNickname}
                                                    ${isSellerReply ? '<span class="seller-tag">商家</span>' : ''}
                                                </div>
                                                <div class="message-time">${new Date(reply.createTime).toLocaleString()}</div>
                                            </div>
                                        </div>
                                        <div class="message-content">
                                            <span class="reply-to">回复 ${message.senderNickname}：</span>
                                            ${reply.content}
                                        </div>
                                        <div class="message-actions">
                                            <button class="reply-btn" onclick="showReplyForm(${message.id}, '${reply.senderNickname}')">
                                                <i class="fas fa-reply"></i> 回复
                                            </button>
                                        </div>
                                    </div>
                                `;
                            }).join('')}
                        </div>
                    ` : ''}
                `;
                messageList.appendChild(messageDiv);
            });
        }

        // 修改显示回复框函数，添加回复对象参数
        function showReplyForm(messageId, replyToName) {
            // 先隐藏所有回复框
            document.querySelectorAll('.reply-form').forEach(form => {
                form.classList.remove('active');
            });
            // 显示当前回复框
            const replyForm = document.getElementById(`replyForm-${messageId}`);
            replyForm.querySelector('textarea').placeholder = `回复 ${replyToName}...`;
            replyForm.classList.add('active');
        }

        // 修改提交复函数，添加回复对象参数
        function submitReply(messageId, replyToName) {
            const replyForm = document.getElementById(`replyForm-${messageId}`);
            const content = replyForm.querySelector('textarea').value.trim();
            
            if (!content) {
                showMessage('请输入回复内容');
                return;
            }

            // 禁用提交按钮，防止重复提交
            const submitButton = replyForm.querySelector('button');
            submitButton.disabled = true;

            $.ajax({
                url: "/message/add",
                type: "POST",
                dataType: "json",
                data: {
                    pid: productId,
                    content: content,
                    receiverId: window.productData.data[0].sellerId,
                    parentId: messageId,
                    replyToName: replyToName
                },
                success: function(response) {
                    if (response.state === 200) {
                        // 清空输入框并隐藏回复框
                        replyForm.querySelector('textarea').value = '';
                        replyForm.classList.remove('active');
                        replyForm.querySelector('textarea').blur(); // 取消输入框焦点

                        // 构造新回复对象
                        const newReply = {
                            id: response.data.id,
                            content: content,
                            createTime: new Date(),
                            senderNickname: response.data.senderNickname,
                            senderAvatar: response.data.senderAvatar,
                            senderId: response.data.senderId
                        };
                        
                        // 找到对应的留言并添加回复
                        const messageContainer = replyForm.closest('.message-item');
                        let replyMessages = messageContainer.querySelector('.reply-messages');
                        
                        // 果还没有回复区域，创建一个
                        if (!replyMessages) {
                            replyMessages = document.createElement('div');
                            replyMessages.className = 'reply-messages';
                            messageContainer.appendChild(replyMessages);
                        }
                        
                        // 添加新回复
                        const replyDiv = document.createElement('div');
                        replyDiv.className = 'message-item';
                        const isSellerReply = newReply.senderId === window.productData.data[0].sellerId;
                        replyDiv.innerHTML = `
                            <div class="message-user-info">
                                <img class="message-avatar" src="${newReply.senderAvatar || 'default-avatar.png'}"
                                     onerror="this.src='default-avatar.png'" alt="用户头像">
                                <div class="message-user-meta">
                                    <div class="message-username">
                                        ${newReply.senderNickname}
                                        ${isSellerReply ? '<span class="seller-tag">商家</span>' : ''}
                                    </div>
                                    <div class="message-time">${new Date(newReply.createTime).toLocaleString()}</div>
                                </div>
                            </div>
                            <div class="message-content">
                                <span class="reply-to">回复 ${replyToName}：</span>
                                ${newReply.content}
                            </div>
                            <div class="message-actions">
                                <button class="reply-btn" onclick="showReplyForm(${messageId}, '${newReply.senderNickname}')">
                                    <i class="fas fa-reply"></i> 回复
                                </button>
                            </div>
                        `;
                        replyMessages.appendChild(replyDiv);
                        
                        // 滚动到新回复的位置
                        replyDiv.scrollIntoView({ behavior: 'smooth', block: 'center' });
                        
                        // 显示成功提示
                        showMessage('回复成功');
                    } else {
                        showMessage(response.msg);
                    }
                },
                complete: function() {
                    // 恢复提交按钮
                    submitButton.disabled = false;
                },
                error: function() {
                    showMessage("请先登录");
                    location.href = "login.html";
                }
            });
        }

        // 添加提示消息函数
        function showMessage(msg) {
            const alert = document.createElement('div');
            alert.className = 'message-alert';
            alert.textContent = msg;
            document.body.appendChild(alert);
            
            // 动画结束后移除提示
            setTimeout(() => {
                alert.remove();
            }, 2000);
        }

        function submitMessage() {
            const content = document.getElementById('messageContent').value.trim();
            if (!content) {
                showMessage('请输入留言内容');
                return;
            }

            $.ajax({
                url: "/message/add",
                type: "POST",
                dataType: "json",
                data: {
                    pid: productId,
                    content: content,
                    receiverId: window.productData.data[0].sellerId
                },
                success: function(response) {
                    if (response.state === 200) {
                        document.getElementById('messageContent').value = '';
                        // 构造新留言对象
                        const newMessage = {
                            id: response.data.id,
                            content: content,
                            createTime: new Date(),
                            senderNickname: response.data.senderNickname,
                            senderAvatar: response.data.senderAvatar,
                            senderId: response.data.senderId,
                            replies: []
                        };
                        
                        // 创建新留言元素
                        const messageDiv = document.createElement('div');
                        messageDiv.className = 'message-item';
                        const isSellerMessage = newMessage.senderId === window.productData.data[0].sellerId;
                        messageDiv.innerHTML = `
                            <div class="message-user-info">
                                <img class="message-avatar" src="${newMessage.senderAvatar || 'default-avatar.png'}" 
                                     onerror="this.src='default-avatar.png'" alt="用户头像">
                                <div class="message-user-meta">
                                    <div class="message-username">
                                        ${newMessage.senderNickname}
                                        ${isSellerMessage ? '<span class="seller-tag">商家</span>' : ''}
                                    </div>
                                    <div class="message-time">${new Date(newMessage.createTime).toLocaleString()}</div>
                                </div>
                            </div>
                            <div class="message-content">${newMessage.content}</div>
                            <div class="message-actions">
                                <button class="reply-btn" onclick="showReplyForm(${newMessage.id}, '${newMessage.senderNickname}')">
                                    <i class="fas fa-reply"></i> 回复
                                </button>
                            </div>
                            <div class="reply-form" id="replyForm-${newMessage.id}">
                                <textarea placeholder="回复 ${newMessage.senderNickname}..."></textarea>
                                <button onclick="submitReply(${newMessage.id}, '${newMessage.senderNickname}')">发送回复</button>
                            </div>
                        `;
                        
                        // 将新留言添加到列表顶部
                        const messageList = document.querySelector('.message-list');
                        messageList.insertBefore(messageDiv, messageList.firstChild);
                        
                        // 显示成功提示
                        showMessage('留言成功');
                    } else {
                        showMessage(response.msg);
                    }
                },
                error: function() {
                    showMessage("请先登录");
                    location.href = "login.html";
                }
            });
        }

        // 在页面加载时获取留言
        $(document).ready(function() {
            getMessages();
        });

        // 添加收藏功能
        $('.favorite').click(function() {
            $.ajax({
                url: "/favorite/add",
                type: "POST",
                data: {
                    productId: productId
                },
                success: function(response) {
                    if(response.state === 1) {
                        // 创建提示框
                        const alertBox = document.createElement('div');
                        alertBox.className = 'alert-box';
                        alertBox.textContent = "收藏成功";
                        document.body.appendChild(alertBox);
                        
                       
                        setTimeout(() => {
                            alertBox.classList.add('fade-out');
                            setTimeout(() => {
                                alertBox.remove();
                            }, 500);
                        }, 1500);

                        // 更新收藏按钮状态
                        $('.favorite').addClass('active');
                    } else {
                        alert(response.msg);
                    }
                },
                error: function() {
                    alert("请先登录");
                    location.href = "login.html";
                }
            });
        });

        // 修改聊天按钮点击事件
        $('.chat').click(function() {
            
            window.open(`chat.html?sellerId=${productData.data[0].sellerId}&productId=${productId}`, '_blank');
                  
        });

        // 添加立即购买功能
        $('.buy-now').click(function() {
            // 跳转到订单确认页面
            location.href = `order-confirm.html?pid=${productId}`;
        });

        function checkFavorite() {
            $.ajax({
                url: '/favorite/check',
                type: 'GET',
                data: { productId: productId },
                success: function(response) {
                    if (response.state === 1) {
                        const isFavorite = response.data;
                        updateFavoriteButton(isFavorite);
                    }
                }
            });
        }

        function toggleFavorite() {
            const action = $('#favoriteBtn').hasClass('favorited') ? 'remove' : 'add';
            $.ajax({
                url: `/favorite/${action}`,
                type: 'POST',
                data: { productId: productId },
                success: function(response) {
                    if (response.state === 1) {
                        updateFavoriteButton(action === 'add');
                        alert(response.msg);
                    } else {
                        alert(response.msg);
                    }
                }
            });
        }

        function updateFavoriteButton(isFavorite) {
            const btn = $('#favoriteBtn');
            if (isFavorite) {
                btn.addClass('favorited').text('已收藏');
            } else {
                btn.removeClass('favorited').text('收藏');
            }
        }

        // 添加图片切换功能
        function switchImage(thumbnail) {
            $('.main-image').attr('src', thumbnail.src);
            $('.thumbnail').removeClass('active');
            $(thumbnail).addClass('active');
        }
    </script>
</body>

</html>